
//////////// 统计执行方法 /////////////

//外部定义http_url,http_fix,http_title

if(typeof http_url === 'undefined'){
	var http_url = document.domain ? document.domain : window.location.host;
}
if(typeof http_fix === 'undefined'){
	var http_fix = '.html';
}
if(typeof http_title === 'undefined'){
	var http_title = '';
}

var zhlC_flag = zhlC_getParam('f');
var zhlC_url = http_url ? http_url+"c_client_save"+http_fix : '';
zhlGoTo(zhlC_url, zhlC_flag);

/////////////////////////////////////

// 开始统计
function zhlGoTo(zhlC_url, zhlC_flag){
	if(!http_url){
		console.log('zhlC_Error');
		return false;
	}
	if (zhlC_flag != 'open') {
		console.log('zhlC_close');
		return false;
	}
	window.onload = function () {
		zhlC_auto(zhlC_url);
	}
}

// 新增访客统计
function zhlC_auto(zhlC_url) {
	console.log('zhlCountGoTo');
	var zhlC_g = zhlC_getScrollTop();
	var zhlC_k = zhlC_getWindowHeight();
	var zhlC_w = zhlC_getBodyHeight();
	// IP
	var zhlC_IP = clientInfo["ip"] !== undefined ? clientInfo["ip"] : '';
	// 目标页面
	var zhlC_page_url = window.location.href;
	var zhlC_page_title = http_title;
	// 百分比
	var zhlC_page_rate = (parseInt(zhlC_g) + parseInt(zhlC_k)) / parseInt(zhlC_w) * 100;
	zhlC_page_rate = zhlC_float2(zhlC_page_rate);
	// 创建时间
	var zhlC_date_start = zhlC_sysDateTime();
	// 来源url
	var zhlC_from_url = document.referrer;
	// 来源系统
	var zhlC_from_os = agentOS();
	// 来源应用
	var zhlC_from_app = agentApp();
	// 新用户标识
	var zhlC_new_user = 'N';
	var zhlC_newcookieDate = zhlC_sysDate();
	var zhlC_cookieDate = zhlC_getCookie('zhlC_new_user');
	if (zhlC_cookieDate != zhlC_newcookieDate) {
		zhlC_new_user = 'Y';
		zhlC_setCookie('zhlC_new_user', zhlC_newcookieDate);
	}
	var zhlC_param = new FormData(); // 实例化创建form表单
	zhlC_param.append("zhlC_IP", zhlC_IP);
	zhlC_param.append("zhlC_new_user", zhlC_new_user);
	zhlC_param.append("zhlC_date_start", zhlC_date_start);
	zhlC_param.append("zhlC_page_url", zhlC_page_url);
	zhlC_param.append("zhlC_page_title", zhlC_page_title);
	zhlC_param.append("zhlC_page_rate", zhlC_page_rate);
	zhlC_param.append("zhlC_from_app", zhlC_from_app);
	zhlC_param.append("zhlC_from_url", zhlC_from_url);
	zhlC_param.append("zhlC_from_os", zhlC_from_os);
	zhlC_param.append("zhlC_action", 'add');
	zhlC_param.append("CMSSTILL", '1');

	zhlC_ajax.post(zhlC_url, zhlC_param,function(r){
		console.log(r);
		if(r.code == 10000){
			let zhlC_temp = { "zhlC_id":r.data.id, "zhlC_table":r.data.table, "zhlC_date_start":zhlC_date_start };
			zhlC_setCookie('zhlC_info', JSON.stringify(zhlC_temp));
			console.log('setcookie');
		}
	},function(e){
		console.log(e);
	});
}

// 滚动时
var zhlC_roll_t1 = 0;
var zhlC_roll_timer = null; // 定时器
var zhlC_g = zhlC_getScrollTop();
window.document.onscroll = function () {
	console.log('RollStart');
	var zhlC_newScrollH = zhlC_getScrollTop();
	if (zhlC_newScrollH > zhlC_g) {
		clearTimeout(zhlC_roll_timer);
		zhlC_roll_t1 = document.documentElement.scrollTop || document.body.scrollTop;
		zhlC_roll_timer = setTimeout(zhlC_isScrollEnd, 500); // 0.5秒后同步
	}
}

// 结束滚动同步
function zhlC_isScrollEnd() {
	console.log('RollEnd');
	let zhlC_tempStr = zhlC_getCookie('zhlC_info');
	let zhlC_temp = JSON.parse(zhlC_tempStr);
	var zhlC_id = zhlC_temp.zhlC_id;
	var zhlC_table = zhlC_temp.zhlC_table;
	var zhlC_date_start = zhlC_temp.zhlC_date_start;
	if(!zhlC_id){
		return false;
	}
	zhlC_roll_t2 = document.documentElement.scrollTop || document.body.scrollTop;
	if (zhlC_roll_t2 == zhlC_roll_t1) {
		console.log('RollEndgo');
		var zhlC_g = zhlC_getScrollTop();
		var zhlC_k = zhlC_getWindowHeight();
		var zhlC_w = zhlC_getBodyHeight();
		var zhlC_page_rate = (parseInt(zhlC_g) + parseInt(zhlC_k)) / parseInt(zhlC_w) * 100;
		zhlC_page_rate = zhlC_float2(zhlC_page_rate);
		var zhlC_date_end = zhlC_sysDateTime();
		var zhlC_IP = clientInfo["ip"] !== undefined ? clientInfo["ip"] : '';
		var zhlC_param2 = new FormData(); // 实例化创建form表单
		zhlC_param2.append("zhlC_IP", zhlC_IP);
		zhlC_param2.append("zhlC_id", zhlC_id);
		zhlC_param2.append("zhlC_date_start", zhlC_date_start);
		zhlC_param2.append("zhlC_date_end", zhlC_date_end);
		zhlC_param2.append("zhlC_page_rate", zhlC_page_rate);
		zhlC_param2.append("zhlC_table", zhlC_table);
		zhlC_param2.append("zhlC_action", 'update');
		zhlC_param2.append("CMSSTILL", '1');
		zhlC_param2.append("flag", '2');
		zhlC_ajax.post(zhlC_url, zhlC_param2,function(r){
			console.log(r);
		},function(e){
			console.log(e);
		});
	}
}

// 页面激活和隐藏
window.addEventListener('visibilitychange', () => {
	if (document.visibilityState === 'visible') { // 页面变为激活状态
		console.log('pageFront');
		//zhlGoTo();
		window.location.reload();
	} else if (document.visibilityState === 'hidden') { // 页面变为隐藏状态
		console.log('pageAfter');
		let zhlC_tempStr = zhlC_getCookie('zhlC_info');
		let zhlC_temp = JSON.parse(zhlC_tempStr);
		var zhlC_id = zhlC_temp.zhlC_id;
		var zhlC_table = zhlC_temp.zhlC_table;
		var zhlC_date_start = zhlC_temp.zhlC_date_start;
		if(!zhlC_id){
			return false;
		}
		var zhlC_g = zhlC_getScrollTop();
		var zhlC_k = zhlC_getWindowHeight();
		var zhlC_w = zhlC_getBodyHeight();
		var zhlC_page_rate = (parseInt(zhlC_g) + parseInt(zhlC_k)) / parseInt(zhlC_w) * 100;
		zhlC_page_rate = zhlC_float2(zhlC_page_rate);
		var zhlC_date_end = zhlC_sysDateTime();
		var zhlC_IP = clientInfo["ip"] !== undefined ? clientInfo["ip"] : '';
		var zhlC_param3 = new FormData(); // 实例化创建form表单
		zhlC_param3.append("zhlC_IP", zhlC_IP);
		zhlC_param3.append("zhlC_id", zhlC_id);
		zhlC_param3.append("zhlC_date_start", zhlC_date_start);
		zhlC_param3.append("zhlC_date_end", zhlC_date_end);
		zhlC_param3.append("zhlC_page_rate", zhlC_page_rate);
		zhlC_param3.append("zhlC_table", zhlC_table);
		zhlC_param3.append("zhlC_action", 'update');
		zhlC_param3.append("CMSSTILL", '1');
		zhlC_param3.append("flag", '3');
		zhlC_ajax.post(zhlC_url,zhlC_param3,function(r){
			console.log(r);
		},function(e){
			console.log(e);
		});
	}
})

// 关闭浏览器
window.addEventListener('beforeunload', function (e) {
	zhlC_isScrollEnd();
});

// 获取滚动条最顶部
function zhlC_getScrollTop(){
    var scrollTop=0;
    if(document.documentElement&&document.documentElement.scrollTop){
        scrollTop=document.documentElement.scrollTop;
    }else if(document.body){
        scrollTop=document.body.scrollTop;
    }
    return scrollTop;
}

// 获取内容总高度
function zhlC_getWindowHeight(){
    var clientHeight=0;
    if(document.body.clientHeight&&document.documentElement.clientHeight){
        var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
    }else{
        var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
    }
    return clientHeight;
}

// 获取body总高度
function zhlC_getBodyHeight(){
    return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
}

// 计算百分比
function zhlC_float2(x) {
	var f = parseFloat(x);
	if (isNaN(f)) {
		return false;
	}
	var f = Math.round(x*100)/100;
	var s = f.toString();
	var rs = s.indexOf('.');
	if (rs < 0) {
		rs = s.length;
		s += '.';
	}
	while (s.length <= rs + 2) {
		s += '0';
	}
	return s;
}

// get now y-m-d
function zhlC_sysDate(){
	var date = new Date();
	return date.getFullYear()+''+parseInt(date.getMonth()+1)+''+date.getDate();
}


// get now y-m-d H:i:s
function zhlC_sysDateTime(){
	let date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth()+1;
	let day = date.getDate();
	let hour = date.getHours();
	let minute = date.getMinutes();
	let second = date.getSeconds();
	return year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
}

// setCookie
function zhlC_setCookie(name,value) {
	// 据说相差8个小时
    var Days = 1; // 有效时间1天
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
	// 据说以下正确方式
	/*var Days = 1; // 有效时间1天
	var exp = new Date(new Date().getTime() + Days*24*60*60*1000);
	document.cookie = name + "="+ escape (value) + ";expires=" + exp*/
}

// getCookie
function zhlC_getCookie(name) {
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg)){
        return unescape(arr[2]);
    }else {
        return null;
	}
}

// 获取url参数字符串转array
function zhlC_getParam(paramName){
	var param;
	var src = document.scripts[document.scripts.length - 1].src;
	var args = src.substr(src.indexOf("?") + 1).split("&");
	for ( var i = 0; i < args.length; i++) {
		var j = args[i].indexOf("=");
		if (j > -1 && args[i].substr(0, j) == paramName) {
			param = args[i].substr(j + 1);
		}
	}
	return param;
}

/**
 * 获取访客系统类型
 */
function agentOS() {
	if(typeof window.navigator.userAgent === "undefined"){
		return 'Other';
	}
	let agent = window.navigator.userAgent.toLowerCase();
	if (agent.indexOf('windows phone') != -1) {
		return 'WindowsPhone';
	}else if (agent.indexOf('harmony') != -1) {
		return 'HarmonyOS';
	} else if (agent.indexOf('ipad') != -1) {
		return 'iPad';
	} else if (agent.indexOf('iphone') != -1) {
		return 'IOS';
	} else if (agent.indexOf('android') != -1) {
		return 'Android';
	} else if (agent.indexOf('mac') != -1) {
		return 'Mac';
	} else if (agent.indexOf('windows') != -1) {
		return 'Windows';
	} else if (agent.indexOf('meego') != -1) {
		return 'MeeGo';
	} else if (agent.indexOf('x11') != -1) {
		return 'Unix';
	} else if (agent.indexOf('linux') != -1) {
		return 'Linux';
	}
	return 'Other';
}

/**
 * 获取访客应用类型
 */
function agentApp() {
	let agent = window.navigator.userAgent.toLowerCase();
	if (agent.indexOf('micromessenger') != -1) {
		return 'WeChat';        // 微信
	} else if (agent.indexOf('alipayclient') != -1) {
		return 'Alipay';        // 支付宝
	} else if (agent.indexOf('qqtheme') != -1) {
		return 'QQ';            // QQ应用
	} else if (agent.indexOf('heytapbrowser') != -1) {
		return 'HeyTapBrowser'; // 欢太浏览器
	} else if (agent.indexOf('vivobrowser') != -1) {
		return 'VivoBrowser';   // vivo浏览器
	} else if (agent.indexOf('mqqbrowser') != -1) {
		return 'MQQBrowser';    // 移动版QQ浏览器
	} else if (agent.indexOf('qqbrowser') != -1) {
		return 'QQBrowser';     // PC版QQ浏览器
	} else if (agent.indexOf('baiduboxapp') != -1) {
		return 'Baidu';         // 百度相关应用
	} else if (agent.indexOf('weibo') != -1) {
		return 'WeiBo';         // 新浪微博
	} else if (agent.indexOf('iqiyi') != -1) {
		return 'IQIYI';         // 爱奇艺
	} else if (agent.indexOf('aweme') != -1) {
		return 'DouYin';        // 抖音
	} else if (agent.indexOf('kdtunion_iting') != -1) {
		return 'Himalaya';      // 喜马拉雅
	} else if (agent.indexOf('dingtalk') != -1) {
		return 'DingTalk';      // 钉钉
	} else if (agent.indexOf('samsungbrowser') != -1 || agent.indexOf('sm-') != -1) {
		return 'SamsungBrowser';// 三星浏览器
	} else if (agent.indexOf('huaweieva') != -1) {
		return 'HuaweiBrowser'; // 华为浏览器
	} else if (agent.indexOf('nokiabrowser') != -1) {
		return 'NokiaBrowser';  // 诺基亚浏览器
	} else if (agent.indexOf('ucbrowser') != -1) {
		return 'UC';            // UC浏览器
	} else if (agent.indexOf('quark') != -1) {
		return 'Quark';         // 夸克浏览器
	} else if (agent.indexOf('metasr') != -1) {
		return 'Sougou';        // 搜狗浏览器
	} else if (agent.indexOf('maxthon') != -1) {
		return 'Maxthon';       // 遨游浏览器
	} else if (agent.indexOf('se 2.x') != -1) {
		return 'SougouExplorer';// 搜狗浏览器
	} else if (agent.indexOf('2345explorer') != -1) {
		return '2345Explorer';  // 2345浏览器
	} else if (agent.indexOf('edg') != -1) {
		return 'Edge';          // Edge浏览器
	} else if (agent.indexOf('msie') != -1 || agent.indexOf('trident') != -1) {
		return 'IE';            // IE浏览器
	} else if (agent.indexOf('firefox') != -1) {
		return 'Firefox';       // 火狐浏览器
	} else if (agent.indexOf('opera') != -1 || agent.indexOf('opr') != -1) {
		return 'Opera';         // 欧朋浏览器
	} else if (agent.indexOf('chrome') != -1) {
		return 'Chrome';        // 谷歌浏览器
	} else if (agent.indexOf('safari') != -1) {
		return 'Safari';        // 苹果浏览器
	}
	return 'Other';
}

// ajax
var zhlC_ajax = {
	get: function(url,data,s,e){
		// XMLHttpRequest对象用于在后台与服务器交换数据
		var xhr=new XMLHttpRequest();
		xhr.open('GET',url+data,false);
		xhr.onreadystatechange=function(){
			// readyState == 4说明请求已完成
			if(xhr.readyState==4){
				if(xhr.status==200 || xhr.status==304){
					console.log(xhr.responseText);
					s(xhr.responseText);
				}else{
					console.log(xhr.responseText);
					e(xhr.responseText);
				}
			}
		}
		xhr.send();
	},
	post: function(url,data,s,e){
		var xhr = new XMLHttpRequest();
		xhr.open('POST',url);
		xhr.onreadystatechange=function(){
			if (xhr.readyState==4){
				if (xhr.status==200 || xhr.status==304){
					console.log(xhr.responseText);
					s(JSON.parse(xhr.responseText));
				}else if(xhr.status>=400){
					console.log(xhr.responseText);
					e(JSON.parse(xhr.responseText));
				}
			}
		}
		xhr.send(data);
	}
};

